package org.dromara.answer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Getter;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.answer.domain.bo.AiUserAnswersBo;
import org.dromara.answer.domain.vo.AiUserAnswersVo;
import org.dromara.answer.domain.AiUserAnswers;
import org.dromara.answer.mapper.AiUserAnswersMapper;
import org.dromara.answer.service.IAiUserAnswersService;
import org.dromara.answer.service.IAiQuestionsService;
import org.dromara.answer.domain.vo.AiQuestionsVo;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户答题记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-04-09
 */
@RequiredArgsConstructor
@Service
public class AiUserAnswersServiceImpl extends ServiceImpl<AiUserAnswersMapper, AiUserAnswers> implements IAiUserAnswersService {

    private final AiUserAnswersMapper baseMapper;
    private final IAiQuestionsService aiQuestionsService;

    /**
     * 查询用户答题记录
     *
     * @param recordId 主键
     * @return 用户答题记录
     */
    @Override
    public AiUserAnswersVo queryById(Long recordId){
        AiUserAnswersVo userAnswer = baseMapper.selectVoById(recordId);
        if (userAnswer != null && userAnswer.getQuestionId() != null) {
            // 通过Java代码关联查询题目信息
            AiQuestionsVo question = aiQuestionsService.queryById(userAnswer.getQuestionId());
            if (question != null) {
                userAnswer.setQuestionTitle(question.getTitle());
                userAnswer.setCorrectAnswer(question.getAnswer());
            }
        }
        return userAnswer;
    }

    /**
     * 分页查询用户答题记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户答题记录分页列表
     */
    @Override
    public TableDataInfo<AiUserAnswersVo> queryPageList(AiUserAnswersBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiUserAnswers> lqw = buildQueryWrapper(bo);
        Page<AiUserAnswersVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        
        // 通过Java代码关联查询题目信息
        for (AiUserAnswersVo userAnswer : result.getRecords()) {
            if (userAnswer.getQuestionId() != null) {
                AiQuestionsVo question = aiQuestionsService.queryById(userAnswer.getQuestionId());
                if (question != null) {
                    userAnswer.setQuestionTitle(question.getTitle());
                    userAnswer.setCorrectAnswer(question.getAnswer());
                }
            }
        }
        
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户答题记录列表
     *
     * @param bo 查询条件
     * @return 用户答题记录列表
     */
    @Override
    public List<AiUserAnswersVo> queryList(AiUserAnswersBo bo) {
        LambdaQueryWrapper<AiUserAnswers> lqw = buildQueryWrapper(bo);
        List<AiUserAnswersVo> userAnswers = baseMapper.selectVoList(lqw);
        
        // 通过Java代码关联查询题目信息
        for (AiUserAnswersVo userAnswer : userAnswers) {
            if (userAnswer.getQuestionId() != null) {
                AiQuestionsVo question = aiQuestionsService.queryById(userAnswer.getQuestionId());
                if (question != null) {
                    userAnswer.setQuestionTitle(question.getTitle());
                    userAnswer.setCorrectAnswer(question.getAnswer());
                }
            }
        }
        
        return userAnswers;
    }

    private LambdaQueryWrapper<AiUserAnswers> buildQueryWrapper(AiUserAnswersBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AiUserAnswers> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AiUserAnswers::getUserId, bo.getUserId());
        lqw.eq(bo.getUserExamId() != null, AiUserAnswers::getUserExamId, bo.getUserExamId());
        lqw.eq(bo.getQuestionId() != null, AiUserAnswers::getQuestionId, bo.getQuestionId());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionType()), AiUserAnswers::getQuestionType, bo.getQuestionType());
        lqw.eq(StringUtils.isNotBlank(bo.getAnswerContent()), AiUserAnswers::getAnswerContent, bo.getAnswerContent());
        lqw.eq(bo.getAnswerTime() != null, AiUserAnswers::getAnswerTime, bo.getAnswerTime());
        lqw.eq(bo.getIsCorrect() != null, AiUserAnswers::getIsCorrect, bo.getIsCorrect());
        lqw.eq(bo.getScoreEarned() != null, AiUserAnswers::getScoreEarned, bo.getScoreEarned());
        return lqw;
    }

    /**
     * 新增用户答题记录
     *
     * @param bo 用户答题记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AiUserAnswersBo bo) {
        AiUserAnswers add = MapstructUtils.convert(bo, AiUserAnswers.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRecordId(add.getRecordId());
        }
        return flag;
    }

    /**
     * 修改用户答题记录
     *
     * @param bo 用户答题记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AiUserAnswersBo bo) {
        AiUserAnswers update = MapstructUtils.convert(bo, AiUserAnswers.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AiUserAnswers entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户答题记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public AiUserAnswersVo queryByQuestionIdAndUserExamId(Long userExamId, Long questionId) {
        LambdaQueryWrapper<AiUserAnswers> lqw = Wrappers.lambdaQuery();
        lqw.eq(AiUserAnswers::getUserExamId, userExamId);
        lqw.eq(AiUserAnswers::getQuestionId, questionId);
        return baseMapper.selectVoOne(lqw);
    }
}
